
//imports
import { homeData, hasDrink, wantDrink, setAPIToken, getSeverUserInfo, wxLogin, Transpond } from '../../../api/eapi';
import util from '../../../utils/util';
import { radar } from '../../templates/canvas.js'


let wxParse = require('../../../wxParse/wxParse.js');

//async status

//页面配置base对象
import base from '../../base';

/**
 * Product Page Config Object
 */
const pageConfig = ({
  data: {
    productId: null,
    product: null,
    showDialog: false,
    addQuantity: 1,
    addType: 'cart',
    numberOfProducts: 0,
    imgurl: "",
    productlist: '',
    infomation: '',
    ateen: true,
    plus: true,
    homeData: '',
    timeout: '',
    geekinfo: false,
    pie: {},
    covers: '',
    article: '',
    eventInput: 0,
    tabData: {
      scroll: false,
      selectedId: 0,
      list: [
        { id: 0, title: "Drink" },
        { id: 1, title: "Geek" }
      ]
    },
    timeline: [
      { type: 'top', pos: 0, text: "\n生产日期" },
      { type: 'bottom', pos: 30, text: "\n最佳适饮时间" },
    ]
    ,
    productdata: {
      title: 'Chateau Pichon Baron de Comt-essde Lalade',
      subtitle: "这款来自法国的世界顶级葡萄酒，是诸",
      year: "2015",
      price: "199.8",
      num: 1,
      id: 1,
      image: 'http://p5txoqjfi.bkt.clouddn.com/image_03.png'
    },
    readMore: 'e'
  },
  gocart() {
    wx.navigateTo({
      url: '../../cart/index?product_list=' + this.data.addType
    })
  },
  submit() {

    wx.navigateTo({
      url: '../../present/index'
    })
  },
  plus(e) {

    if (e.currentTarget.dataset.button == "true") {
      let te = {};
      let n = this.data.productdata.num;
      if (n > 1) {
        te["productdata.num"] = n - 1;
        this.setData(te)
      };
      if (n == 2) this.setData({
        plus: true
      })
    } else {
      let te = {};
      let n = this.data.productdata.num
      te["productdata.num"] = n + 1;
      this.setData(te);
      this.setData({
        plus: false
      })
    }
  },
  menubox() {
    this.setData({
      ateen: true
    })
  },
  gofriend() {
    this.setData({
      ateen: false
    })

  },
  Back() {
    wx.navigateBack({
      delta: 1
    })
  },
  WantDrink(e) {
    let _this = this;
    wx.showLoading({
      title: '请稍候',
    })
    if (e.currentTarget.dataset.drink == 'true') {
      let aten = new Promise(function (resolve, reject) {
        if (_this.data.homeData.user_has_drink) {
          hasDrink.delete({ ids: _this.data.homeData.id }).then(res => {
            resolve('已取消')
          });
        } else {
          hasDrink.post({ id: _this.data.homeData.id }).then(res => {
            resolve('已加入')
          })
        };
      }).then(res => {
        wx.hideLoading();
        wx.showToast({
          title: res,
          icon: 'success'
        })
        let obj = {
          'homeData.user_has_drink': _this.data.homeData.user_has_drink ? null : 'e'
        };
        _this.setData(obj)
      })

    } else {

      new Promise(function (resolve, reject) {
        if (_this.data.homeData.user_want_drink) {
          wantDrink.delete({ ids: _this.data.homeData.id }).then(res => {
            resolve('已取消')
          })
        } else {
          wantDrink.post({ id: _this.data.homeData.id }).then(res => {
            resolve('已加入')
          })
        };
      }).then(res => {
        wx.hideLoading();
        wx.showToast({
          title: res,
          icon: 'success'

        })
        let obj = {
          'homeData.user_want_drink': _this.data.homeData.user_want_drink ? null : 'e'
        };
        _this.setData(obj)
      })

    };

    setTimeout(function () {
      wx.hideLoading();
    }, 5000);

    wx.setStorage({
      key: 'drink',
      data: true
    })
  },
 

  _handleZanQuantityPlus: function (e) {
    console.log(e)
    if (this.data.addQuantity < this.data.product.stock) {
      this.setData({
        addQuantity: this.data.addQuantity + 1
      })
    }
  },

  _handleZanQuantityMinus: function (e) {
    if (this.data.addQuantity > 1) {
      this.setData({
        addQuantity: this.data.addQuantity - 1
      })
    }
  },
  /**
   * On Dialog OK
   */
  toogleDialog: function (e) {
    let addType = util.isEmpty(e) ? "cart" : e.currentTarget.dataset.addType;

    this.setData({
      showDialog: !this.data.showDialog,
      addType: addType
    });
  },
  /**
   * On Dialog OK
   */
  onOK: function () {
    //立即购买
    // if (this.data.addType == "checkout") {
    let product = this.data.product;



    this.addToOrder([{
      productId: product.id,
      quantity: this.data.addQuantity,
      sellerId: product.seller.id
    }]);
    this.requireAuthUrl("/pages/checkout/index");

    //收起购物车
    this.toogleDialog();
  },

  onReady: function (e) {
    let _this = this;
    this.data.timeout.then(res => {
      let c = this.data.homeData;
      let talkAbout = c.drink.talk_about;
      let drinkinfo = [
        { icon: '/images/general_img_varieties@2x.png', name: c.category },
        { icon: '/images/general_img_brew@2x.png', name: c.blend_deployment.length == 1 ? c.blend_deployment[0].name : '混酿' },
        { icon: '/images/general_img_level@2x.png', name: c.level },
        { icon: '/images/general_img_alcohol@2x.png', name: c.degree + '%' }]

      let covers = [];

      for (let p = 1; p < c.covers.length; p++) {
        covers.push(c.covers[p])
      };

      let list = c.relation_products;
      list.forEach((item, index) => {
        item.collect = item.user_want_drink ? true : false;
        item.drink = item.user_has_drink ? true : false;
        item.list = true;
      });

      _this.setData({
        productlist: list,
        infomation: drinkinfo,
        covers: covers
      });

      let talk = wxParse.wxParse('article', 'html', talkAbout, _this, 0);

      _this.setData(talk);

      wx.setStorage({
        key: 'productData',
        data: c
      });

      let drink = {
        acidity: c.acidity,
        sweetness: c.sweetness,
        bitter: c.bitter,
        degree: c.degree_score,
        aftertaste: c.aftertaste,
        winebody: c.wine_body,
        Intensity: c.Intensity,
        complexity: c.complexity
      };

      for (var i in drink) {
        drink[i] = Number(drink[i])
      };


      let dat = [drink.acidity * 10, drink.sweetness * 10, drink.bitter * 10, drink.degree * 10]

      wx.createSelectorQuery().select('.canvas').boundingClientRect(function (bac) {

        let datTitle = ["酸度", "甜度", "涩度", "酒精度"];
        let width = 0;
        let linewidth = 0;
        var fo = 0
        wx.getSystemInfo({
          success: function (res) {
            width = res.screenWidth / 750 * 225;
            linewidth = res.screenWidth / 750 * 30
            fo = res.screenWidth / 750 * 28;//字体
          },
        })

        let canvasId = ["pie-1", "pie-2", "pie-3", "pie-4"];

        for (let a = 0; a < 4; a++) {
          var ctx = wx.createCanvasContext(canvasId[a]);

          ctx.beginPath()
          const grd = ctx.createLinearGradient(width, 0, 0, width);
          grd.addColorStop(0, '#BD1241');
          grd.addColorStop(1, '#771650');
          ctx.setLineWidth(linewidth)
          ctx.setLineCap('round')
          ctx.setStrokeStyle(grd);
          ctx.arc(width / 2 + linewidth / 2, width / 2 + linewidth / 2, width / 2, Math.PI * 1.5, Math.PI * (dat[a] / 50 + 1.5), false);
          ctx.stroke();

          ctx.beginPath();
          ctx.setFontSize(fo);
          ctx.setFillStyle("#000000");
          ctx.setTextAlign("center");
          ctx.setTextBaseline("middle")
          ctx.fillText(datTitle[a], width / 2 + linewidth / 2, width / 2 + linewidth / 2);

          ctx.beginPath();
          ctx.setLineWidth(linewidth)
          ctx.setStrokeStyle("rgba(120,28,88,0.1)");
          ctx.arc(width / 2 + linewidth / 2, width / 2 + linewidth / 2, width / 2, 0, Math.PI * 2, false);
          ctx.stroke();
          ctx.closePath();

          ctx.draw(false, function () {
            wx.canvasToTempFilePath({
              canvasId: canvasId[a],
              success: function (res) {
                let data = {};
                data["pie.image" + a] = res.tempFilePath
                _this.setData(data)

              },
              template: function (e) {
                console.log(e)
              }
            })
          }
          );

        }

      }).exec();

      radar(drink).then(res => {
        _this.setData({
          imgurl: res.tempFilePath
        })
      })

      let vintage = this.data.homeData.vintage,
        uptime = this.data.homeData.upTime,
        untime = this.data.homeData.unTime;
      let line = [vintage, uptime];

      let timeline = this.data.timeline.map((evl, index) => {
        evl.text = line[index] + evl.text
        return evl
      });

      this.setData({
        timeline: timeline
      });

    })
  },
  /**
   * 页面加载函数
   * 
   * @param options 传入参数对象
   */
  onLoad: function (options) {
    let _this = this;
    let ID = options.product;
    let parr = new Promise(function (resolve, reject) {
      if (options.q) {
        wxLogin('扫码').then(res => {
          let code = options.q;
          code = code.split('%2F');
          code = code[code.length - 1];
          homeData("drink-from-code", { data: { code: code } }).then(res => {
            resolve(res.data.data[0]);
            _this.setData({
              homeData: res.data.data[0]
            })
          });
        })
      } else if (options.product) {
        let body = {
          detail: true
        };
        homeData("drink/" + ID, {data:body}).then(res => {
          resolve(res.data.data);
          _this.setData({
            homeData: res.data.data
          })

        })
      } else {
        let code = options.code;
        code = code.split('/');
        code = code[code.length - 1];
        homeData("drink-from-code", { data: { code: code } }).then(res => {
          resolve(res.data.data[0]);
          _this.setData({
            homeData: res.data.data[0]
          })
       
        });
      }
    });

    this.setData({
      timeout: parr
    })


  },

  onTabChange: function (e) {
    let ds = e.currentTarget.dataset;
    this.setData({
      tabData: Object.assign({}, this.data.tabData, { selectedId: ds.itemId }),
      geekinfo: ds.itemId
    });

  },
  collect(e) {
    let homeData = this.data.productlist;
    let id = e.currentTarget.dataset.image;
    wx.showLoading({
      title: 'loading',
    });
    homeData.forEach(item => {
      if (item.id === id) {
        // 改变想喝的状态
        if (item.collect) {
          wantDrink.delete({ ids: id }).then(resp => {
            console.log(resp);
            item.collect = false;

            // 更新状态
            this.setData({ productlist: homeData }, () => wx.hideLoading());
          }).catch(err => console.error(err))
        } else {
          // 改变不想喝的状态
          wantDrink.post({ id: id }).then(resp => {
            console.log(resp);
            item.collect = true;

            // 更新状态
            this.setData({ productlist: homeData }, () => wx.hideLoading());
          }).catch(err => console.error(err))
        }
      }
    });
  },
  drink(e) {
    let homeData = this.data.productlist;
    let id = e.currentTarget.dataset.image;
    wx.showLoading({
      title: 'loading',
    });
    homeData.forEach(item => {
      if (item.id === id) {
        // 改变喝过的状态
        if (item.drink) {
          hasDrink.delete({ ids: id }).then(resp => {
            console.log(resp);
            item.drink = false;

            // 更新状态
            this.setData({ productlist: homeData }, () => wx.hideLoading());
          }).catch(err => console.error(err))
        } else {
          // 改变没喝过的状态
          hasDrink.post({ id: id }).then(resp => {
            console.log(resp);
            item.drink = true;

            // 更新状态
            this.setData({ productlist: homeData }, () => wx.hideLoading());
          }).catch(err => console.error(err))
        }
      }
    });
  },
  selectChange(e) {
    this.setData({
      eventInput: e.detail.currentItemId
    });

  },
  readMore(e) {
    let _this = this;
    let n = e.currentTarget.dataset.type;
    let a = _this.data.readMore;

    if (a == n) {
      _this.setData({
        readMore: 'e'
      })
    } else {
      _this.setData({
        readMore: n
      })
    }

  },

  onShareAppMessage: function (res) {
    res['from'] = 'button';
    res.target = {
      dataset: {
        type: `2,${this.data.homeData.id},${this.data.homeData.banner},${this.data.homeData.chname}`
      }
    }

    return Transpond(res)
  },
  onUnload:function(){
    let pages=getCurrentPages();
    if(pages[0].route.match(/QRcode/)){
      wx.switchTab({
        url: '/pages/catalog/product-listing/index'
      })
    }
  }
});



Page(pageConfig);
